package org.netty.push.appinfo.service.impl;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

import org.apache.commons.lang3.time.DateUtils;
import org.netty.push.api.dto.Token;
import org.netty.push.appinfo.dao.AppInfoRepository;
import org.netty.push.appinfo.domian.AppInfo;
import org.netty.push.appinfo.service.AppInfoService;
import org.netty.push.core.proto.ConnectRequestMsg;
import org.netty.push.core.proto.ConnectResponseMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AppInfoServiceImpl implements AppInfoService {
	Logger logger=LoggerFactory.getLogger(AppInfoServiceImpl.class);
	
	@Autowired
	private AppInfoRepository appInfoRepository;
	
	@Override
	public ConnectResponseMsg doConnected(ConnectRequestMsg ConnectRequestMsg) {
		logger.info("ConnectRequestMsg is {}",ConnectRequestMsg);
		ConnectResponseMsg connectResponseMsg=new ConnectResponseMsg();
		
		String deviceToken=UUID.randomUUID().toString();
		connectResponseMsg.setDeviceToken(deviceToken);
		connectResponseMsg.setId(UUID.randomUUID().toString());
		return connectResponseMsg;
	}
	
	@Override
	public Token getToken(String appId, String appKey, String appSecret) {
		Optional<AppInfo> appInfo=appInfoRepository.findById(appId);
		if(appInfo.get()!=null) {
			if(appInfo.get().getAppKey().equalsIgnoreCase(appKey)) {
				Token token=new Token();
				token.setToken(UUID.randomUUID().toString());

				Date expire=DateUtils.addDays(new Date(), 1);
				token.setExpire(expire.getTime());
				return token;
			}
		}
		return null;
	}

}
